<template>
  <div class="w-full h-full overflow-hidden">
    <div class="w-350px mt-70px bg-white px-14px py-15px ml-auto mr-auto rounded-4px">
      <div
        :class="{
          'h-204px': skus.length + comboSkus.length >= 3,
          'overflow-y-scroll invisible-scrollbar': skus.length + comboSkus.length > 3
        }"
      >
        <div
          v-for="sku in skus"
          :key="sku.id"
          class="flex items-center justify-between h-60px mb-12px"
        >
          <div class="w-60px h-60px" style="border-radius: 4px 4px 0px 0px">
            <img
              :src="sku.url"
              alt=""
              class="w-60px h-60px"
              style="border-radius: 4px 4px 0px 0px"
            />
          </div>
          <div
            class="flex-1 flex flex-col ml-7px"
            :class="{ 'pr-12px': skus.length + comboSkus.length > 3 }"
          >
            <div class="text-16px font-medium h-24px leading-24px" style="color: #3e3e3e">
              {{ sku.name }}
            </div>
            <div class="text-10px h-15px leading-15px mt-4px" style="color: #9d9d9d">
              {{
                sku.combination
                  ? JSON.parse(sku.combination).reduce((prev, cur) => (prev += cur.value), '')
                  : ''
              }}
            </div>
            <div class="flex items-center justify-between mt-5px">
              <div class="text-10px h-15px leading-15px" style="color: #9d9d9d">
                x {{ sku.number }}
              </div>
              <div style="color: #818181" class="text-16px">
                <span class="text-12px">￥</span>{{ sku.number * sku.price }}
              </div>
            </div>
          </div>
        </div>
        <div
          v-for="sku in comboSkus"
          :key="sku.id"
          class="flex items-center justify-between h-60px mb-12px"
        >
          <div class="w-60px h-60px" style="border-radius: 4px 4px 0px 0px">
            <img
              :src="sku.img?.[0]"
              alt=""
              class="w-60px h-60px"
              style="border-radius: 4px 4px 0px 0px"
            />
          </div>
          <div
            class="flex-1 flex flex-col ml-7px"
            :class="{ 'pr-12px': skus.length + comboSkus.length > 3 }"
          >
            <div class="text-16px font-medium h-24px leading-24px" style="color: #3e3e3e">
              {{ sku.name }}
            </div>
            <div class="text-10px h-15px leading-15px mt-4px" style="color: #9d9d9d">
              {{
                sku.skus
                  ? sku.skus.reduce(
                      (acc, s) =>
                        (acc += JSON.parse(s.combination || '[]')?.reduce(
                          (prev, cur) => (prev += cur.value + ','),
                          ''
                        )),
                      ''
                    )
                  : ''
              }}
            </div>
            <div class="flex items-center justify-between mt-5px">
              <div class="text-10px h-15px leading-15px" style="color: #9d9d9d">
                x {{ sku.number }}
              </div>
              <div style="color: #818181" class="text-16px">
                <span class="text-12px">￥</span>{{ cart.totalComboOriginPrice }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="flex items-center justify-between mt-29px">
        <div class="text-16px h-19px leading-19px">优惠券</div>
        <div v-if="coupons.length" class="text-12px color-coupon">{{ coupons.length }}张可用</div>
        <div v-else style="color: #999" class="text-12px">暂无优惠券可用</div>
      </div>
      <div
        class="mt-12px"
        :class="{
          'h-157px': coupons.length >= 2,
          'overflow-y-scroll invisible-scrollbar pr-12px': coupons.length > 2
        }"
      >
        <div
          v-for="(coupon, index) in coupons"
          :key="coupon.id"
          class="h-72px rounded-5px bg-white flex px-13px py-6px items-center mb-13px"
          :class="{ 'w-306px': coupons.length > 2 }"
          style="border: 1px solid #ededed; box-shadow: -1px 2px 2px rgba(0, 0, 0, 0.25)"
        >
          <div class="color-coupon text-10px w-120px">
            <div class="text-14px font-medium h-17px leading-17px text-black">
              {{ coupon.name }}
            </div>
            <div v-if="coupon.validity_type == 1" class="mt-10px">
              {{ coupon.validity_begin }} ~ {{ coupon.validity_end }}
            </div>
            <div v-else class="mt-10px">
              {{ dayjs(coupon.userCoupons?.create_at).format('YYYY.MM.DD') }} ~
              {{
                dayjs(coupon.userCoupons?.create_at)
                  .add(coupon.validity_day, 'day')
                  .format('YYYY.MM.DD')
              }}
            </div>
          </div>
          <div
            v-if="coupon.discount_type == 3"
            class="flex-1 text-right color-coupon text-16px font-bold"
          >
            {{ coupon.discount_index }}折
          </div>
          <div
            v-if="coupon.discount_type == 2"
            class="flex-1 text-right color-coupon text-16px font-bold"
          >
            -{{ coupon.discount_number }}元
          </div>
          <div
            v-if="coupon.discount_type == 1"
            class="flex-1 text-right color-coupon text-16px font-bold"
          >
            满{{ coupon.discount_condition_match }}减{{ coupon.discount_condition_minus }}
          </div>
          <div
            class="w-18px h-18px rounded-[50%] ml-19px relative cursor-pointer"
            style="border: 1px solid #9b9b9b"
            @click="selectCoupon(index)"
          >
            <div v-if="activeCoupon === index" class="absolute left-3px top-3px w-12px h-12px">
              <img :src="SelectedCouponIcon" alt="" class="w-12px h-12px" />
            </div>
          </div>
        </div>
      </div>
      <!-- <div
        v-if="!user.level"
        class="color-coupon text-14px h-21px leading-21px cursor-pointer"
        @click="openlevel"
      >
        开通VIP可领取更多优惠劵 >
      </div> -->
      <div class="flex" :class="{ 'mt-20px': !user.level, 'mt-17px': user.level }">
        <div class="text-14px mt-10px" style="color: #686868">实付金额：</div>
        <div class="flex-1">
          <div>
            <span class="color-coupon text-28px font-bold">{{ total }}</span> 元
          </div>
          <div
            v-if="discount || minus || cart.totalComboOriginPrice - cart.totalComboDiscountPrice"
            class="text-12px"
            style="color: #999"
          >
            已优惠￥
            <span class="text-16px font-medium">{{
              (discount || minus) + (cart.totalComboOriginPrice - cart.totalComboDiscountPrice)
            }}</span>
            元
          </div>
        </div>
        <div
          class="w-102px h-31px bg-coupon text-white rounded-27px leading-31px text-center cursor-pointer"
          @click="gopay"
        >
          立即支付
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useCartStore } from '@renderer/store/modules/cart'
import useHttp from '@renderer/utils/http'
import { onMounted, computed, ref } from 'vue'
import SelectedCouponIcon from '@renderer/assets/selectCoupon.svg'
import { useUserStore } from '@renderer/store/modules/user'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'

const activeCoupon = ref<any>()

const router = useRouter()
const route = useRoute()

let skuId: any = null

const CouponType = [
  {
    label: '商品券',
    value: 1
  },
  {
    label: '充值券',
    value: 2
  },
  {
    label: '上网券',
    value: 3
  },
  {
    label: '酒店券',
    value: 4
  },
  {
    label: '麻将券',
    value: 5
  },
  {
    label: '台球券',
    value: 6
  }
]

const cart = useCartStore()
const user = useUserStore()
const skus = computed(() => {
  return cart.getSelectedSkus
})
const comboSkus = computed(() => {
  return cart.getSelectedComboSkus
})
// 充多少送多少
let giveFee = 0
const total = ref<number>(0)
const discount = ref<number>(0)
const minus = ref<number>(0)

const coupons = ref<any>([])

onMounted(async () => {
  const { data: res } = await useHttp('/coupon/sku_user')
    .post({
      spuIds: skus.value.map((sku) => sku.spu_id)
    })
    .json()
  if (res.value.code === 200) {
    const matchminusCoupons = res.value.data.filter((coupon) => coupon.discount_type == 1)
    calculatePartTotal({}, 0)
    const noMatchminusCoupons = matchminusCoupons.filter((coupon) => {
      const canSelectedSpus = JSON.parse(coupon.include_spu)
      const matchedSkus = cart.getSelectedSkus.filter((sku) =>
        canSelectedSpus.some((spu) => spu.value === sku.spu_id)
      )
      const matchTotal = matchedSkus.reduce((acc, sku) => {
        acc += Number(sku.number) * Number(sku.price)
        return acc
      }, 0)
      return matchTotal < coupon.discount_condition_match
    })

    coupons.value = res.value.data.filter((coupon) => {
      return !noMatchminusCoupons.find((noMatchminusCoupon) => noMatchminusCoupon.id === coupon.id)
    })
  }
})
const calculatePartTotal = (excludeSku, dis) => {
  discount.value = dis
  total.value =
    cart.getSelectedSkus.reduce((acc, cur) => {
      if (cur.id === excludeSku.id) {
        acc += excludeSku.price - dis + excludeSku.price * (excludeSku.number - 1)
      } else {
        acc += cur.price * cur.number
      }
      return acc
    }, 0) + cart.totalComboDiscountPrice || 0
}
const selectCoupon = (index) => {
  if (activeCoupon.value === index) {
    activeCoupon.value = null
    calculatePartTotal({}, 0)
  } else {
    activeCoupon.value = index
    // 每个商品只能使用一张优惠券
    const selectedCoupon = coupons.value[index]
    const canSelectedSpus = JSON.parse(selectedCoupon.include_spu)
    const matchedSkus = cart.getSelectedSkus.filter((sku) =>
      canSelectedSpus.some((spu) => spu.value === sku.spu_id)
    )
    let finalDiscount = 0
    let finalSku: any = null
    if (selectedCoupon.discount_type == 3) {
      // 打折
      const discountIndex = selectedCoupon.discount_index
      matchedSkus.forEach((matchedSku) => {
        if (finalDiscount < matchedSku.price * ((10 - discountIndex) / 10)) {
          finalDiscount = matchedSku.price * ((10 - discountIndex) / 10)
          finalSku = matchedSku
        }
      })
      skuId = [finalSku?.id]
      minus.value = 0
      giveFee = 0
      calculatePartTotal(finalSku, Math.floor(finalDiscount))
    } else if (selectedCoupon.discount_type == 2) {
      const discountNumber = selectedCoupon.discount_number
      matchedSkus.forEach((matchedSku) => {
        if (finalDiscount < matchedSku.price - discountNumber) {
          finalDiscount = discountNumber
          finalSku = matchedSku
        }
      })
      skuId = [finalSku?.id]
      minus.value = 0
      giveFee = 0
      calculatePartTotal(finalSku, finalDiscount)
    } else if (selectedCoupon.discount_type == 1) {
      const matchTotal = matchedSkus.reduce((acc, sku) => {
        acc += Number(sku.number) * Number(sku.price)
        return acc
      }, 0)
      skuId = matchedSkus.map((sku) => sku.id)
      discount.value = 0
      giveFee = 0
      minus.value = selectedCoupon.discount_condition_minus
      total.value = matchTotal - selectedCoupon.discount_condition_minus
    } else if (selectedCoupon.discount_type == 4) {
      // 充多少送多少
      skuId = [matchedSkus?.[0]?.id]
      minus.value = 0
      discount.value = 0
      giveFee = selectedCoupon.give_fee
    }
  }
}
// 去支付
const gopay = () => {
  console.log(skuId, minus.value, discount.value, total.value)
  router.replace({
    name: 'Pay',
    query: {
      from: route.query.from,
      coupons: coupons.value?.[activeCoupon.value]?.id,
      price: total.value,
      discount: discount.value,
      total: total.value,
      minus: minus.value,
      giveFee,
      skuId,
      comboDiscount: cart.totalComboOriginPrice - cart.totalComboDiscountPrice
    }
  })
}
// 开通会员
const openlevel = () => {
  router.replace({ name: 'Vip' })
}
</script>

<style scoped>
.invisible-scrollbar::-webkit-scrollbar {
  width: 3px;
  background: #fff;
  height: 3px;
  display: block;
}
.invisible-scrollbar::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background: #e6e6e6;
  display: block;
}
</style>
